package com.bdqn.t330.ch07.controller;

import com.bdqn.t330.ch07.entity.Role;
import com.bdqn.t330.ch07.entity.User;
import com.bdqn.t330.ch07.servcie.RoleService;
import com.bdqn.t330.ch07.servcie.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
@Controller
public class UserController {

    @Resource
    UserService userService;

    @Resource
    RoleService roleService;

    @RequestMapping("/list")
    public String list() {
        return "/user/list";
    }

    @RequestMapping("/getlist")
    public Object getlist(Model model,
                          @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
                          @RequestParam(value = "usrName", required = false, defaultValue = "") String usrName,
                          @RequestParam(value = "roleId", required = false, defaultValue = "0") Long roleId) {
        // List<User> list = userService.getListService(pa)
        // model.addAttribute("list",list);
        Pageable pageable = PageRequest.of(pageIndex - 1, 5);
        Map<String, Object> map = new HashMap<>();
        map.put("usrName", usrName);
        map.put("roleId", roleId);
        Page<User> page = userService.getListService(map, pageable);

        List<Role> roleList = roleService.getRoleList();

        model.addAttribute("page", page);
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleList", roleList);
        model.addAttribute("roleId", roleId);
        return "/user/list";
    }

    @GetMapping("/toadd")
    public String toAdd() {
        return "/user/add";
    }

    @PostMapping("/save")
    public String save(User user) {
        User user1 = userService.saveService(user);
        if (user1 == null) {
            return "/user/add";
        } else {
            return "redirect:/user/getlist";
        }
    }

    @GetMapping("/toedit")
    public String toedit(Long usrId, Model model) {
        User user = userService.findByUserIdService(usrId);
        model.addAttribute("user", user);
        return "/user/edit";
    }

    @RequestMapping(value = "/del")
    @ResponseBody
    public Map del(Long usrId) {
        Map map = new HashMap();
        try {
            userService.deleteUserService(usrId);
            map.put("delResult", "true");
        } catch (Exception e) {
            map.put("delResult", "false");
            e.printStackTrace();
        }
        return map;
    }
}
